package yxy.game.pm2.command.union.leader;

import yxy.apple.util.StringUtillity;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.UnionLeaderMessage;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;

/** 联盟盟主 联盟公告修改 */
@MessageType(proto = Command.UnionNoticeRemend, classtype = UnionLeaderMessage.UnionNoticeRemendRequest.class)
public class CMD_UnionNoticeRemend extends Command<UnionLeaderMessage.UnionNoticeRemendRequest> {

	@Override
	public void execute(MessageSource messageSource, UnionLeaderMessage.UnionNoticeRemendRequest request) {
		String playerCode = messageSource.getTag();
		String notice = request.getNotice();

		UnionLeaderMessage.UnionNoticeRemendResponse.Builder response = UnionLeaderMessage.UnionNoticeRemendResponse.newBuilder();

		// 管理员权限
		UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
		Result result = new UnionHandle().checkPlayerUnionManager(entry);
		if (!result.equals(Result.UnionManager)) {
			send(messageSource, response, result);
			return;
		}

		// 字符检查 字符整形 全角改半角 敏感词检查
		notice = StringUtillity.toDBC(notice).trim();
		result = new UnionHandle().checkNotice(notice);
		if (!result.equals(Result.Success)) {
			send(messageSource, response, result);
			return;
		}

		RedisLock uLock = UnionBean.lock(entry.getUnionBean().getCode());
		try {
			if (uLock.tryLock()) {
				UnionBean union = entry.reloadUnionBean();

				union.setNotice(notice);
				union.set();
				union.active();

				if (union.getNotice() != null) {
					response.setNotice(union.getNotice());
				}
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			uLock.unlock();
		}
	}

	private void send(MessageSource messageSource, UnionLeaderMessage.UnionNoticeRemendResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}